package com.game.hall.processor;

import com.game.message.Msg;
import com.game.message.connetion.ConnectionManager;
import com.game.common.MsgSendHelper;
import com.game.message.jpb.JPbUtil;
import com.game.message.messagecode.HallMsg;
import com.game.message.messagecode.MsgStage;
import com.game.message.task.IAsynProcessor;
import com.game.message.task.IProcessor;
import com.game.messagebean.hall.LoginReq;
import com.game.messagebean.hall.LoginResp;
import com.game.mongo.User;
import com.game.mongo.UserMongo;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by legend9999 on 2016/4/25.
 */
@Component
public class LoginProcessor extends RedPackBaseProcessor{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public int getMsgId() {
        return MsgStage.REQ + HallMsg.LOGIN;
    }

    public Msg process(Msg msg, ChannelHandlerContext playerClientCtx) {
        LoginReq pb = JPbUtil.getPb(LoginReq.class, msg);
        logger.info(pb.toString());
        String loginName = pb.getLoginName();
        String password = pb.getPassword();
        LoginResp respBean = new LoginResp();
        User user = userMongo.findByLoginName(loginName);
        if (user == null) {
            user = new User(loginName, password);
            user.setUserId(userMongo.getNextUserId());
            userMongo.addUser(user);
        } else if (!user.getPassword().equals(password)) {
            respBean.setResult(false);
            respBean.setMessage("password error");
            MsgSendHelper.sendMsg(user.getUserId(), JPbUtil.getMsg(LoginResp.class, respBean));
            return null;
        }
        respBean.setResult(true);
        respBean.setMessage("login success");
        respBean.setServerTime(System.currentTimeMillis());
        //登录成功，session中保存用户id
        ConnectionManager.getInstance().create(playerClientCtx, user.getUserId(),pb.getGameId());
        MsgSendHelper.sendMsg(user.getUserId(), JPbUtil.getMsg(LoginResp.class, respBean));
        logger.info(user + " login success...");
        return null;
    }

}
